   /**
    * Removes spaces on beggining and in the end of string
    */
   function trim(string) {
       var ltrim = /^\s+/g;
       var rtrim = /\s+$/g;
       string = string.replace(ltrim,'');
       string = string.replace(rtrim,'');
       return string;
   }
   /**
    * Count shipping price according to users data (AJAX)
    * @param reload <boolean> shows to reload page or not.
    * @return void
    */
    function countShipping(reload){
        var urlwebsite = $('#hid-main-wsurl').val();
        var shippingData = {
            firstname : trim($('#shipping-firstname').val()),
            lastname : trim($('#shipping-lastname').val()),
            company : trim($('#shipping-company').val()),
            email : trim($('#shipping-email').val()),
            address1 : trim($('#shipping-address1').val()),
            address2 : trim($('#shipping-address2').val()),
            city : trim($('#shipping-city').val()),
            state : null!==$('#shipping-state').val()?$('#shipping-state').val():'',
            zip : trim($('#shipping-zip').val()),
            country : trim($('#shipping-country').find('option:selected').text()),
            phone : trim($('#shipping-phone').val()),
            mobile : trim($('#shipping-mobile').val()),
			instructions : trim($('#shipping-instructions').val())
        };
		if (shippingData.email == '' || !shippingData.email.match(/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})$/i) ) {
            $('#shipping-email').css('border-color','red');
            return false;
        } else {
            $('#shipping-email').css('border-color','#7c7c7c');
        }
        $('.payment-gateway-email').val(shippingData.email);
        
        var shippAddr = '';
        shippAddr    += (shippingData.firstname != '' ? shippingData.firstname : '');
        shippAddr    += (shippingData.lastname != '' ? ' ' + shippingData.lastname + '<br />' : '<br />');
        shippAddr    += (shippingData.company != '' ? shippingData.company + '<br />' : '');
        shippAddr    += (shippingData.address1 != '' ? shippingData.address1 : '');
        shippAddr    += (shippingData.address1 != '' && shippingData.address2 != '' ? ', ' : '');
        shippAddr    += (shippingData.address2 != '' ? shippingData.address2 : '');
        shippAddr    += '<br />';
        shippAddr    += (shippingData.city != '' ? shippingData.city : '');
        shippAddr    += (shippingData.city != '' && (shippingData.state != '' || shippingData.zip != '') ? ', ' : '');
        shippAddr    += (shippingData.state !='' ? shippingData.state : '');
        shippAddr    += (shippingData.state !='' ? ' ' : '');
        shippAddr    += (shippingData.zip != '' ? shippingData.zip : '');
        shippAddr    += '<br />';
        shippAddr    += (shippingData.country != '' ? shippingData.country : '');

        $.ajax({
            async: false,
            type : 'post',
            url : urlwebsite +'sys/backend_shipping/calculate/',
            dataType : 'json',
            data : ({
                shippingService : $('#shipping-service').val(),
                firstname : shippingData.firstname,
                lastname : shippingData.lastname,
				company : shippingData.company,
                email : shippingData.email,
                address1 : shippingData.address1,
                address2 : shippingData.address2,
                city : shippingData.city,
                state : shippingData.state,
                zip : shippingData.zip,
                country : $('#shipping-country').val(),
                phone : shippingData.phone,
                mobile : shippingData.mobile,
				instructions: shippingData.instructions
            }),
            beforeSend : function(){
                $('#startmsg').html('Calculating shipping value...');
                $('#startmsg').show();
            },
            complete : function(){
            },
            success: function(shipping){
                if ( shipping[0] instanceof Object) {
                    ShippingMultiSelect(shipping);
                    $('#startmsg').hide();
                }
                if (shipping.type == 'pickup' || shipping.type == 'error'){
                    if (shipping.type == 'error' && undefined!==shipping.descr) 
                        if (shipping.descr.length > 0) $("#startmsg").html(shipping.descr)
                    return;
                } else {
                    var newVal = shipping.price ? parseFloat(shipping.price) : 0;
                    $('#shipping-value').text(newVal.toFixed(2));
                    //$('#credit-card-shipping').val(newVal);
                    //$('input:hidden[name="shipping"]').val(newVal);
                    $('.payment-gateway-shipping').val(newVal);
                }
                $('#shipping-info-form').slideUp('slow');
                $('shippAddr-default').hide();
                $('#shipping-info-title-default').hide();
                $('#shipping-info-title-proccessed').show();
                $('#checkout').hide();
				$('<span>', {id: 'current-shipping-address'})
					.css({display: 'block', marginLeft: '30px', textTransform: 'none'})
					.html(shippAddr)
					.appendTo('#shipping-info-title');
                $('.cart-pay').show('slow');
                $("#startmsg").html("Your Shipping Cost has been calculated.");
                $('input.qty-item').attr('disabled',true);
                $('a.rem-item').hide();
                window.setTimeout('$("#startmsg:visible").hide()', 5000);
                if (true === reload){
                    top.location.reload();
                }
            }
            });

    }

    /**
     * Shipping form validator
     * if form validated countShipping() called
     * 
     * @return void
     */
    function validateShippingForm(){
        var error = new Array();
        var shippingAddr = '';

        if (trim($('#shipping-firstname').val()) == '') {
            $('#shipping-firstname').css('border-color','red');
            error.push(1);
        } else {
            $('#shipping-firstname').css('border-color','#7c7c7c');
        }
		var email =trim($('#shipping-email').val());
        if (email == '' || !email.match(/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})$/i) ) {
            $('#shipping-email').css('border-color','red');
            error.push(1);
        } else {
            $('#shipping-email').css('border-color','#7c7c7c');
        }
        if (trim($('#shipping-address1').val()) == '') {
            $('#shipping-address1').css('border-color','red');
            error.push(1);
        } else {
            $('#shipping-address1').css('border-color','#7c7c7c');
        }
        /*if (trim($('#shipping-address2').val()) == '') {
            $('#shipping-address2').css('border-color','red');
            error.push(1);
        } else {
            $('#shipping-address2').css('border-color','#7c7c7c');
        }*/
        if (trim($('#shipping-city').val()) == '') {
            $('#shipping-city').css('border-color','red');
            error.push(1);
        } else {
            $('#shipping-city').css('border-color','#7c7c7c');
        }
        /*if ($('#shipping-state').val() == '') {
            $('#shipping-state').css('border-color','red');
            error.push(1);
        } else {
            $('#shipping-state').css('border-color','#7c7c7c');
        }*/
        if (trim($('#shipping-zip').val()) == '' || isNaN(trim($('#shipping-zip').val()))) {
            $('#shipping-zip').css('border-color','red');
            error.push(1);
        } else {
            $('#shipping-zip').css('border-color','#7c7c7c');
        }
        if ($('#shipping-country').val() == '') {
            $('#shipping-country').css('border-color','red');
            error.push(1);
        } else {
            $('#shipping-country').css('border-color','#7c7c7c');
        }

        if (($('#shipping-country').val() == 'US' || $('#shipping-country').val() == 'CA') && $('#shipping-state').val() == '') {
            $('#shipping-state').css('border-color','red');
            error.push(1);
        } else {
            $('#shipping-state').css('border-color','#7c7c7c');
        }

        if (error.length > 0) {
            return;
        }

        countShipping(false);
    }

    function copyShippingData(formname)
    {
        switch (formname) {
        case 'paypal-creditcard':
            $('#credit-card-firstname').val($('#shipping-firstname').val());
            $('#credit-card-lastname').val($('#shipping-lastname').val());
			$('#credit-card-company').val($('#shipping-company').val());
            $('#credit-card-email').val($('#shipping-email').val());
            $('#credit-card-billing-address1').val($('#shipping-address1').val());
            $('#credit-card-billing-address2').val($('#shipping-address2').val());
            $('#credit-card-country').val($('#shipping-country').val()).change();
            $('#credit-card-state').val($('#shipping-state').val());
            $('#credit-card-city').val($('#shipping-city').val());
            $('#credit-card-zip').val($('#shipping-zip').val());
            $('#credit-card-phone').val($('#shipping-phone').val());
            
            break;
        case 'form_quote':
			$('#cart-quote-firstname').val($('#shipping-firstname').val());
            $('#cart-quote-lastname').val($('#shipping-lastname').val());
			$('#cart-quote-company').val($('#shipping-company').val());
            $('#cart-quote-email').val($('#shipping-email').val());
            $('#cart-quote-address1').val($('#shipping-address1').val());
            $('#cart-quote-address2').val($('#shipping-address2').val());
            $('#cart-quote-country').val($('#shipping-country').val()).change();
            $('#cart-quote-state').val($('#shipping-state').val());
            $('#cart-quote-city').val($('#shipping-city').val());
            $('#cart-quote-zip').val($('#shipping-zip').val());
            $('#cart-quote-phone').val($('#shipping-phone').val());

            break;

        default:
            break;
        }
    }

    function ShippingMultiSelect(list){
        var $el = $('<div></div>', {id : 'shipping-multiselect'});
        
		$.each(list, function (index, listItem){
			var $inp = $('<input />', {type: 'radio', name: 'shms', value: listItem.price}) ,
				$span = $('<span></span>').html( $('<span></span>').html(listItem.type).text() ) ,
				$label = $('<label></label>', {style: "float:right", html: listItem.price});
			$('<p></p>').append($inp).append($span).append($label).appendTo($el);
		})

        $($el).append('<button class="formsubmit" onclick="javascript:userAcceptShipping();">OK</button>')

        $('#seotoaster.cartview').append('<div id="SHMS_overlay" />')
            .append($el)
        $($el).show()
    }

    function userAcceptShipping(){
        var urlwebsite = $('#hid-main-wsurl').val();
        var el = $('#shipping-multiselect').find('input:radio:checked')
        
		if (! el.size() ){
			return false;
		}
		
        $.ajax({
            url: urlwebsite + 'sys/backend_shipping/setuserselectedshipper/',
            type: 'POST',
            dataType: 'json',
            data: {
                type: el.next('span').text(),
                price: el.val()
            },
            success: function(responce){
                var newVal = responce.price;
                $('#shipping-value').text(''+newVal+'');
                $('#credit-card-shipping').val(newVal);
                $('input:hidden[name="shipping"]').val(newVal);
                recountTotal();
            }
        })
        $('#SHMS_overlay').remove()
        $('#shipping-multiselect').remove()
    }